package com.hengtuo.kaiyuanzhongguo;

import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.widget.RadioButton;
import android.widget.Toast;

import com.google.android.gms.common.api.GoogleApiClient;
import com.hengtuo.fragment.Comprehensive_Fragment;
import com.hengtuo.fragment.Find_Fragment;
import com.hengtuo.fragment.Mine_Fragment;
import com.hengtuo.fragment.Moveball_Fragment;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends FragmentActivity {
    private Toolbar toolbar;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private FragmentManager fm;
    private FragmentTransaction ft;
    //自定义的弹出框类
    SelectPicPopup menuWindow;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;
    private RadioButton rb_comprehensive;
    private RadioButton rb__moveball;
    private RadioButton rb_find;
    private RadioButton rb__mine;
    private RadioButton jia;
    private Comprehensive_Fragment comprehensiveFragment;
    private Moveball_Fragment moveballFragment;
    private Find_Fragment findFragment;
    private Mine_Fragment mineFragment;
    private static final int CHOOSE_PICTURE=100;
    private static final int PHOTO_WITH_CAMERA=100;
    private static final int TAKE_PICTURE = 0;
    private static final int SCALE = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViews(); //获取控件

        sideslip();

        init();

    }

    private void init() {

        fm = getSupportFragmentManager();

        ft = fm.beginTransaction();
        comprehensiveFragment =new Comprehensive_Fragment();
        moveballFragment = new Moveball_Fragment();
        findFragment = new Find_Fragment();
        mineFragment = new Mine_Fragment();

        ft.add(R.id.fragment_lord, comprehensiveFragment);
        ft.add(R.id.fragment_lord, moveballFragment);
        ft.add(R.id.fragment_lord, findFragment);
        ft.add(R.id.fragment_lord, mineFragment);
        ft.hide(moveballFragment).hide(findFragment).hide(mineFragment);
        ft.commit();

        button();


    }

    private void button() {
        //综合
        rb_comprehensive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fm.beginTransaction().show(comprehensiveFragment).hide(moveballFragment).hide(findFragment).hide(mineFragment).commit();
            }
        });
        //动弹
        rb__moveball.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fm.beginTransaction().show(moveballFragment).hide(comprehensiveFragment).hide(findFragment).hide(mineFragment).commit();
            }
        });
        //发现
        rb_find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fm.beginTransaction().show(findFragment).hide(comprehensiveFragment).hide(moveballFragment).hide(mineFragment).commit();
            }
        });
        //我
        rb__mine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fm.beginTransaction().show(mineFragment).hide(comprehensiveFragment).hide(moveballFragment).hide(findFragment).commit();
            }
        });

       jia.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               menuWindow = new SelectPicPopup(MainActivity.this, itemsOnClick);
               //显示窗口
               menuWindow.showAtLocation(MainActivity.this.findViewById(R.id.jia), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
           }
       });
    }
    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.ll_photo:
                    Toast.makeText(MainActivity.this, "相册", Toast.LENGTH_SHORT).show();
                    Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);

                    openAlbumIntent.setType("image/*");

                    startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
                    break;
                case R.id.ll_note:
                    Toast.makeText(MainActivity.this, "便签", Toast.LENGTH_SHORT).show();
                    break;

                case R.id.ll_erweima:
                    Toast.makeText(MainActivity.this, "扫一扫", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.ll_wenzi:
                    

                    break;
                case R.id.ll_paizhao:
                    Toast.makeText(MainActivity.this, "相机", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //调用系统相机
                    Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"image.jpg"));

                    //指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换

                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    //直接使用，没有缩小
                    startActivityForResult(intent, PHOTO_WITH_CAMERA);  //用户点击了从相机获取
                    break;
                case R.id.ll_yuyin:
                    Toast.makeText(MainActivity.this, "语音", Toast.LENGTH_SHORT).show();
                    break;
            }


        }

    };
    private void sideslip() {


        // toolbar.setTitle("开源中国");//设置Toolbar标题
        // toolbar.setTitleTextColor(Color.parseColor("#ffffff")); //设置标题颜色

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.open, R.string.close);
        mDrawerToggle.syncState();
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        //   comprehensiveFragment = new Comprehensive_Fragment(); arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, lvs);
        //   lvLeftMenu.setAdapter(arrayAdapter);


    }

    private void findViews() {

        toolbar = (Toolbar) findViewById(R.id.tl_custom);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.dl_left);
      //  lvLeftMenu = (ListView) findViewById(R.id.lv_left_menu);
        rb_comprehensive = (RadioButton) findViewById(R.id.rb_comprehensive);
        rb__moveball = (RadioButton) findViewById(R.id.rb__moveball);
        rb_find = (RadioButton) findViewById(R.id.rb_find);
        rb__mine = (RadioButton) findViewById(R.id.rb__mine);
        jia= (RadioButton) findViewById(R.id.jia);

    }

    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {

            switch (requestCode) {

                case TAKE_PICTURE:

                    //将保存在本地的图片取出并缩小后显示在界面上

                    Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/image.jpg");
                    Bitmap newBitmap = zoomBitmap(bitmap, bitmap.getWidth() / SCALE, bitmap.getHeight() / SCALE);



                    //由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常

                    bitmap.recycle();

                    //将处理过的图片显示在界面上，并保存到本地

                   // iv_image.setImageBitmap(newBitmap);

                    savePhotoToSDCard(newBitmap, Environment.getExternalStorageDirectory().getAbsolutePath(), String.valueOf(System.currentTimeMillis()));

                    break;

                case CHOOSE_PICTURE:
                    ContentResolver resolver = getContentResolver();
                    //照片的原始资源地址

                    Uri originalUri = data.getData();
                    //使用ContentProvider通过URI获取原始图片

                    Bitmap photo = null;
                    try {
                        photo = MediaStore.Images.Media.getBitmap(resolver, originalUri);
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    if (photo != null) {

                        //为防止原始图片过大导致内存溢出，这里先缩小原图显示，然后释放原始Bitmap占用的内存50

                        Bitmap smallBitmap = zoomBitmap(photo, photo.getWidth() / 10, photo.getHeight()/10);

                        //释放原始图片占用的内存，防止out of memory异常发生

                        photo.recycle();



                     //   iv_image.setImageBitmap(smallBitmap);
                        break;

                    }

            }
        }

    }
    public Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {

        int w = bitmap.getWidth();

        int h = bitmap.getHeight();

        Matrix matrix = new Matrix();

        float scaleWidth = ((float) width / w);

        float scaleHeight = ((float) height / h);

        matrix.postScale(scaleWidth, scaleHeight);// 利用矩阵进行缩放不会造成内存溢出

        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);

        return newbmp;

    }
    public static void savePhotoToSDCard(Bitmap photoBitmap, String photoName,

                                         String path) {

        if (android.os.Environment.getExternalStorageState().equals(

                android.os.Environment.MEDIA_MOUNTED)) {

            File dir = new File(path);

            if (!dir.exists()) {

                dir.mkdirs();

            }

            File photoFile = new File(path, photoName); //在指定路径下创建文件

            FileOutputStream fileOutputStream = null;

            try {

                fileOutputStream = new FileOutputStream(photoFile);

                if (photoBitmap != null) {

                    if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100,

                            fileOutputStream)) {

                        fileOutputStream.flush();

                    }

                }

            } catch (FileNotFoundException e) {

                photoFile.delete();

                e.printStackTrace();

            } catch (IOException e) {

                photoFile.delete();

                e.printStackTrace();

            } finally {

                try {

                    fileOutputStream.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }
}
